package com.ruoyi.warning.ding;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiMediaUploadRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMediaUploadResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.warning.domain.dto.ConfigurationDTO;
import com.ruoyi.warning.domain.entity.Contacts;
import com.ruoyi.warning.domain.entity.Message;
import com.ruoyi.warning.service.IContactsService;
import com.ruoyi.warning.service.IMessageService;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.common.enums.WarningSendStatus.FAILURE;
import static com.ruoyi.common.enums.WarningSendStatus.SUCCESS;

@Component
@Service
public class DingTalkWorkNoticeUtils {
    @Resource
    private IMessageService messageService;
    @Resource
    private IContactsService contactsService;
    @Resource
    private SysDictDataMapper sysDictDataMapper;



    private static final String GET_TOKEN_URL = "https://oapi.dingtalk.com/gettoken";
    private static final String GET_BY_MOBILE = "https://oapi.dingtalk.com/topapi/v2/user/getbymobile";
    private static final String ASYNC_SEND_V2_URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2";
//    private static final String DEFAULT_APP_KEY = "dingrorzuswskyavbhnt";
//    private static final String DEFAULT_APP_SECRET = "w9rWIVzvIID0pdPszGRP1h3oQgaMG4ZjV4cnR-hK-a41TM8ZXccYdTqn1ggO3ESr";
//    private static final Long DEFAULT_AGENT_ID = 2806009094L;
//    private static final String DEFAULT_REQUEST_METHOD = "GET";
    private static final String UPLOAD_MEDIA_URL = "https://oapi.dingtalk.com/media/upload";

//    private String appKey = "dingrorzuswskyavbhnt";
//    private String appSecret = "w9rWIVzvIID0pdPszGRP1h3oQgaMG4ZjV4cnR-hK-a41TM8ZXccYdTqn1ggO3ESr";
//    private Long agentId = 2806009094L;
//    private String reqMethod = "GET";


//    public DingTalkWorkNoticeUtils() {
//        this(DEFAULT_APP_KEY, DEFAULT_APP_SECRET, DEFAULT_AGENT_ID, DEFAULT_REQUEST_METHOD);
//    }
//
//    public DingTalkWorkNoticeUtils(String appKey, String appSecret, Long agentId, String reqMethod) {
//        this.appKey = (appKey != null && !appKey.isEmpty()) ? appKey : DEFAULT_APP_KEY;
//        this.appSecret = (appSecret != null && !appSecret.isEmpty()) ? appSecret : DEFAULT_APP_SECRET;
//        this.agentId = (agentId != null) ? agentId : DEFAULT_AGENT_ID;
//        this.reqMethod = (reqMethod != null && !reqMethod.isEmpty()) ? reqMethod : DEFAULT_REQUEST_METHOD;
//    }


    // 获取AccessToken
    public String getTokenResponse() throws ApiException {
        List<SysDictData> dictList = sysDictDataMapper.selectDictDataByType("dingding_setting");
        Map<String, String> map = dictList.stream()
                .collect(Collectors.toMap(
                        item -> item.getDictLabel(),
                        item -> item.getDictValue()
                ));
        DingTalkClient client = new DefaultDingTalkClient(GET_TOKEN_URL);
        OapiGettokenRequest req = new OapiGettokenRequest();
        req.setAppkey(map.get("accessKeyId"));
        req.setAppsecret(map.get("accessKeySecret"));
        req.setHttpMethod("GET");
        OapiGettokenResponse rsp = client.execute(req);
        return rsp.getAccessToken();
    }

    // 根据手机号获取UserId
    public String getUserIdByMobile(String accessToken, String mobileNum) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(GET_BY_MOBILE);
        OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
        req.setMobile(mobileNum);
        OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);

        JSONObject jsonObject = JSON.parseObject(rsp.getBody());
        System.out.println("+++++++++++++++++++++++++++++");
        System.out.println(rsp.getBody());
        JSONObject result = jsonObject.getJSONObject("result");
        if (ObjectUtils.isEmpty(result.getString("userid"))) {
            System.out.println("未查询到用户信息");
            return null;
        }
        String userid = result.getString("userid");
        return userid;
    }

    // 发送工作通知消息
    public boolean sendWorkNoticeText(String accessToken, String content, ConfigurationDTO configurationDTO) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(ASYNC_SEND_V2_URL);
        OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
        String agentId = sysDictDataMapper.selectDictValue("dingding_setting","agentId");
        req.setAgentId(Long.valueOf(agentId.trim()));
        List<String> dingList = new java.util.ArrayList<>();
        //检测是否所有人都有钉钉号
//        for(Contacts contact : configurationDTO.getContacts()){
//            if(ObjectUtils.isEmpty(contact.getDingding())){
//                String userid = getUserIdByMobile(accessToken, contact.getPhoneNumber());
//                if(ObjectUtils.isEmpty(contact.getDingding())){
//                    contact.setDingding("未知");
//                    contactsService.updateById(contact);
//                    continue;
//                }
//                contact.setDingding(userid);
//                contactsService.updateById(contact);
//                dingList.add(userid);
//            }else {
//                dingList.add(contact.getDingding());
//            }
//        }

        // 在代码中使用
        for(Contacts contact : configurationDTO.getContacts()){
            System.out.println("处理联系人: {}, 手机号: {}"+contact.getContactsName()+contact.getPhoneNumber());

            if(ObjectUtils.isEmpty(contact.getDingding())||contact.getDingding().equals("未知")){
                System.out.println("+++++++++++++++++++++");
                System.out.println("+++++++++++++++++++++");
                System.out.println("+++++++++++++++++++++");
                System.out.println("+++++++++++++++++++++");
                System.out.println("+++++++++++++++++++++");
                System.out.println("+++++++++++++++++++++");
                String userid = getUserIdByMobile(accessToken, contact.getPhoneNumber());

                if(ObjectUtils.isEmpty(userid)){
                    System.out.println("未获取到钉钉ID，设置为'未知'");
                    contact.setDingding("未知");
                    contactsService.updateById(contact);
                } else {
                    System.out.println("获取到钉钉ID: "+userid);
                    contact.setDingding(userid);
                    contactsService.updateById(contact);
                    dingList.add(userid);
                }
            } else {
                System.out.println("已有钉钉ID:"+contact.getDingding());
                dingList.add(contact.getDingding());
            }
        }
        req.setUseridList(String.join(",", dingList));

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("text");
        OapiMessageCorpconversationAsyncsendV2Request.Text text = new OapiMessageCorpconversationAsyncsendV2Request.Text();
        text.setContent(content);
        msg.setText(text);
        req.setMsg(msg);

        OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, accessToken);

        List<Message> list = new java.util.ArrayList<>();
        Integer status = FAILURE.getCode();
        if("ok".equals(rsp.getErrmsg())){
            status = SUCCESS.getCode();
        }
        //保存告警信息
        for(Contacts contact : configurationDTO.getContacts()){
            Message message = new Message();
            message.setDeviceName(configurationDTO.getDeviceName());
            message.setAreaId(configurationDTO.getAreaId());
            message.setAreaName(configurationDTO.getAreaName());
            message.setWarningType(configurationDTO.getWarningType());
            message.setWarningStatus(status);
            message.setWarningWay(1);
            message.setWarningLevel(configurationDTO.getWarningLevel());
            message.setWarningContact(contact.getContactsName());
            message.setWarningContent(configurationDTO.getDeviceName()+" 告警:"+configurationDTO.getTitle());
            message.setEventId(configurationDTO.getEventId());
            message.setEventDetailId(configurationDTO.getEventDetailId());
            list.add(message);
        }
        messageService.saveBatch(list);
        return rsp.isSuccess();
    }

    public boolean sendWorkNoticePic(String accessToken, String mediaId, ConfigurationDTO configurationDTO) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(ASYNC_SEND_V2_URL);

        OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
        String agentId = sysDictDataMapper.selectDictValue("dingding_setting","agentId");
        req.setAgentId(Long.valueOf(agentId.trim()));
        List<String> dingList = new java.util.ArrayList<>();
        //检测是否所有人都有钉钉号
        for(Contacts contact : configurationDTO.getContacts()){
            if(ObjectUtils.isEmpty(contact.getDingding())
                    ||contact.getDingding().equals("未知")
                    ||contact.getDingding().equals("0")){
                String userid = getUserIdByMobile(accessToken, contact.getPhoneNumber());
                if(ObjectUtils.isEmpty(contact.getDingding())){
                    contact.setDingding("未知");
                    contactsService.updateById(contact);
                    continue;
                }
                contact.setDingding(userid);
                contactsService.updateById(contact);
                dingList.add(userid);
            }else {
                dingList.add(contact.getDingding());
            }
        }
        req.setUseridList(String.join(",", dingList));

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();

        msg.setMsgtype("image");
        msg.setImage(new OapiMessageCorpconversationAsyncsendV2Request.Image());
        msg.getImage().setMediaId(mediaId);
        req.setMsg(msg);

        OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, accessToken);
        return rsp.isSuccess();
    }

    public boolean sendWorkNoticeFile(String accessToken, String mediaId, ConfigurationDTO configurationDTO) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(ASYNC_SEND_V2_URL);

        OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
        String agentId = sysDictDataMapper.selectDictValue("dingding_setting","agentId");
        req.setAgentId(Long.valueOf(agentId.trim()));
        List<String> dingList = new java.util.ArrayList<>();
        //检测是否所有人都有钉钉号
        for(Contacts contact : configurationDTO.getContacts()){
            if(ObjectUtils.isEmpty(contact.getDingding())){
                String userid = getUserIdByMobile(accessToken, contact.getPhoneNumber());
                if(ObjectUtils.isEmpty(contact.getDingding())){
                    contact.setDingding("未知");
                    contactsService.updateById(contact);
                    continue;
                }
                contact.setDingding(userid);
                contactsService.updateById(contact);
                dingList.add(userid);
            }else {
                dingList.add(contact.getDingding());
            }
        }
        req.setUseridList(String.join(",", dingList));

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();

        msg.setMsgtype("file");
        msg.setFile(new OapiMessageCorpconversationAsyncsendV2Request.File());
        msg.getFile().setMediaId(mediaId);
        req.setMsg(msg);

        OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, accessToken);
        return rsp.isSuccess();
    }

    public String uploadMedia(String accessToken, String mediaType, File file) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(UPLOAD_MEDIA_URL);
        OapiMediaUploadRequest request = new OapiMediaUploadRequest();
        request.setType(mediaType);
        FileItem fileItem = new FileItem(file);
        request.setMedia(fileItem);

        OapiMediaUploadResponse response = client.execute(request, accessToken);
        if (response.isSuccess()) {
            JSONObject jsonObject = JSONObject.parseObject(response.getBody());
            return jsonObject.getString("media_id");
        } else {
            System.err.println("上传媒体文件失败: " + response.getErrmsg());
            return null;
        }
    }

    public static void main(String[] args) throws ApiException {
        // 德业还是ikd忘了
//        String appKey = "dinggya608qic6qrh25f";
//        String appSecret = "Fzyn0J9eYp0uakZpnUHCcgE66qAlp5f-IOn31LCQscvFJAzynNXf5JclE0iI1_PE";
        String appKey = "dingrorzuswskyavbhnt";
        String appSecret = "w9rWIVzvIID0pdPszGRP1h3oQgaMG4ZjV4cnR-hK-a41TM8ZXccYdTqn1ggO3ESr";
        String reqMethod = "GET";

        DingTalkClient dclient = new DefaultDingTalkClient(GET_TOKEN_URL);
        OapiGettokenRequest dreq = new OapiGettokenRequest();
        dreq.setAppkey(appKey);
        dreq.setAppsecret(appSecret);
        dreq.setHttpMethod(reqMethod);
        OapiGettokenResponse drsp = dclient.execute(dreq);
        String accessToken = drsp.getAccessToken();
        System.out.println(accessToken);

        DingTalkClient client = new DefaultDingTalkClient(GET_BY_MOBILE);
        OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
        req.setMobile("18067229555");
        OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);

        JSONObject jsonObject = JSON.parseObject(rsp.getBody());
        JSONObject result = jsonObject.getJSONObject("result");
        System.out.println(result);
        if (result == null) {
            System.out.println("未查询到用户信息");
        }
        String userid = result.getString("userid");
        System.out.println(userid);



        DingTalkClient client1 = new DefaultDingTalkClient(ASYNC_SEND_V2_URL);

        OapiMessageCorpconversationAsyncsendV2Request req1 = new OapiMessageCorpconversationAsyncsendV2Request();
        // 德业还是ikd忘了
//        req1.setAgentId(2607840466L);
        req1.setAgentId(2806009094L);

        req1.setUseridList(userid);

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("text");
        OapiMessageCorpconversationAsyncsendV2Request.Text text = new OapiMessageCorpconversationAsyncsendV2Request.Text();
        text.setContent("这是一条测试信息");
        msg.setText(text);
        req1.setMsg(msg);

        OapiMessageCorpconversationAsyncsendV2Response rsp1 = client1.execute(req1, accessToken);

        System.out.println(rsp1.isSuccess());
        System.out.println(rsp1.getBody());

    }
}



